
function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
var cstm_id = GetQueryString('Id_data');
console.log(cstm_id)
$(document).ready(function(){
	    //		权限判断
		if($.cookie('ID') == null){
			window.location.href="http://www.duoweish.com/crm/login.html";
		}
//		2，3号权限
		if($.cookie('Right') == 1){
			window.location.href="http://www.duoweish.com/crm/index.html";
		}
		
		
//////////////////////		1001363//左边基本信息及功能
		       
		       
				 $.ajax({
						headers:{
  							Accept:"application/json;charset=utf-8"
  								},
  					type:"get",
  					data:{
  						UserId:$.cookie('ID'),
  						Id:cstm_id
  					},
  					url:"http://www.duoweish.com/apis/CstmDetail/",
  					success:function (data){
  						
  						start_view(data)
  				
			  				 
  							
		
  					}
  			
				})
		 //页面渲染函数
		 function start_view(data){
		 	      var view_inp = $("#phone_infor").find("textarea");
		 				for (var i = 0;i<view_inp.length;i++) {
			  				
			  							view_inp.eq(i).val(data[1][i]);
			  						
			  		}
		 			/*$('#select1').val(['1']).trigger('change');*/
		 			$("#base_infor").find("input").eq(0).val(data[0][0])
		 			$("#base_infor").find("input").eq(1).val(data[0][1])
		 			$(".sel_credit").val([data[0][2]]).trigger('change');
		 			$(".sale_nation").val(data[0][3]).trigger('change');
		 			$(".sale_way").val(data[0][4]).trigger('change');
		 			$(".store_kind").val(data[0][5]).trigger('change');
		 			$(".sale_kind").val(data[0][6]).trigger('change');
		 			$(".adv_way").val(data[2][0]).trigger('change');
		 			
		 			$(".sale_adress").val(data[2][3]).trigger('change');
		 			
		 			$(".sale_time").parent().find(".select2-selection__rendered").text(data[2][1]);
		 			$(".sale_num").parent().find(".select2-selection__rendered").text(data[0][7]);
		 			$(".sale_price").parent().find(".select2-selection__rendered").text(data[0][8]);
		 			
		 			$(".sale_mark").find("textarea").html(data[2][2])
		 			////sale_time
		 			 for (var i=0;i<data[3].length;i++) {
											if(data[7][i]!=""){
												$(".business_text").find("textarea").eq(i).val(data[3][i])
											}
								}
		 			 //最近修改人
				    for (var i=0;i<data[7].length;i++) {
													if(data[7][i]!=""){
														var Label = "<li>"+data[7][i]+"</li>";
														$(".alter_person").append(Label)
													}
									}
				    
		           if(data[6]==0){
  								$(".business_text").find('textarea').attr('readonly','readonly');
  						    	}
		            //电话权限
		            if(data[4]==0){
		      	
		      	
							if(data[5].length > 0){
  								if( data[5].indexOf('12') != -1){
  									$(".phone[mun='12']").val(data[1][4]);
		  							}else{
		  								console.log($('.cstm_phone'))
		  								$(".phone[mun='12']").val('***********');
		  								$('.cstm_phone').append('<i class="fa fa-eye float-right click_eye1"></i>');
		  								
		  								
		  							}
  								if( data[5].indexOf('18') != -1){
		  									$(".phone[mun='18']").val(data[1][6]);
		  							}else{
		  								$(".phone[mun='18']").val('***********');
		  								$('.room_phone').append('<i class="fa fa-eye float-right click_eye2"></i>');
		  							}

  							}else{
  									$(".phone").val('***********');
  									$('.cstm_phone').append('<i class="fa fa-eye float-right click_eye1"></i>');
  									$('.room_phone').append('<i class="fa fa-eye float-right click_eye2"></i>');
  							}
  						}
		            //查看电话号码事件
		           $('.click_eye1').click(function(){
		                     apply_phone('12')     			
		           })
		           $('.click_eye2').click(function(){
		                     apply_phone('18')     			
		           })
  						
		 }
		
		//申请查看电话
		function apply_phone(num){
			                  $.ajax({
	  									type:"get",
	  									url:"http://www.duoweish.com/apis/CstmDetailApply/",
	  									
	  									data:{
	  										UserId:$.cookie('ID'),
	  										Cstm:cstm_id,
	  										Num:num
	  									
	  									},
	  									success:function(data){
	  										if(data == "success"){
	  											layer.msg('申请成功');
	  										}else{
	  											layer.msg('已申请，请耐心等待审批，勿重复提交');
	  										}

	  									}
	  									
	  								}) 
		                  }
		
		$(".select_body").hide()
		$(".guide_replay").hide()
		var sel_length = $(".sel_ul").find("input").length;
		var sel_inp = $(".sel_ul").find("input");
		
		$(".open_icon").click(function(){
			$(".select_body").toggle()
		})
		 $(".select_body").find("li").click(function(){
		 	$(".select_body").hide()
		 })
		
		 $('.select2').select2();
		 

		 //退出
		 $(".return_icon").click(function(){
		 
		 	parent.$(".content-wrapper").show();
		 	
		 	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index); 
		 })
		 //提交修改基本信息
		 
		$(".submit").click(function(){
		  layer.prompt({
				formType: 2,
				title: '请输入修改备注',
				area: ['300px', '150px']
			}, function(text, index, value) {
				
				
				var sel_M = [];
				var more_Sel = $("select[index='1']");
				
				for (var i = 0;i<more_Sel.length;i++) {
					var now_sel = more_Sel.eq(i).select2("data");
					var Arr = [];
					for (var j = 0;j<now_sel.length;j++) {
						var Text =now_sel[j].text;
						Arr.push(Text);
					}
					sel_M.push(Arr);
					Arr = [];
					 
				}
				
				formData = new FormData(document.getElementById("myform"));
				formData.append("credit", $(".sel_credit").select2("val"));//信用
				formData.append("sale-number", $(".sale_num").select2("val"));//月销售笔数
				formData.append("sale-price", $(".sale_price").select2("val"));//客单价
				
	     		formData.append("sale-nature", sel_M[0].join(","));//销售性质
	     		formData.append("sale-way",sel_M[1].join(","));//销售渠道
	     		formData.append("store-kind", sel_M[2].join(","));//店铺类别store_kind
	     		formData.append("sale-kind", sel_M[3].join(","));//售卖类别sale_kind
	     		formData.append("adv-way", sel_M[4].join(","));//宣传渠道
	     		formData.append("receive", sel_M[5].join(","));//接受地
	     		formData.set("file", $("#upload")[0].files[0]);
	     		formData.append("UserId", $.cookie('ID'));
	     		formData.append("Cstm", cstm_id);
	     	    formData.append("pay-time",$(".sale_time").parent().find(".select2-selection__rendered").text());//账期
				formData.append("lable-data", text)
	            layer.close(index);
				 layer.confirm('是否要保存修改',function(index){
				  	submit();
				  	layer.close(index)
				  	
				  },function(index){layer.close(index)},{skin:'demo-class'})
	
			})
		 
			
		})
	  function submit(){
				
				$.ajax({
					type: "POST",
					url: "http://www.duoweish.com/apis/CstmUpdateSubmit/",
					data: formData,
					processData: false,
					contentType: false,
					success: function(data) {
						layer.msg('提交成功')
					}
			
				});
	
		}
	$('#upload').change(function(){
		$(this).parent().append('<span class="float-right pic_ha">已选择一张图片</span>')
	})
	     /////////////////////////////////////////////////右边列表
		//图片放大
	  $(".event_img").find("img").click(function(){
	  	$(".big_img_src").attr("src",$(this).attr("src"))
		   $(".big_img").slideDown("slow");
		   $(".img_all_screen").click(function(){
		   		$(".big_img_src").css({"height":"100%","width":"100%"})
		   		$(".big_img").css({"height":"100%","width":"100%","left":"0","margin-left":"0"})
		   	   
		   })
		   $(".close_big_img").click(function(){ 
		   		$(".big_img").hide();
		   		
		   		$(".big_img_src").css({"height":"450px","width":"600px"})
		   		$(".big_img").css({"width":"800px","left":"-400px","margin-left":"50%"})
		   	    
		   })
	  })

							    
			
			
			
		//tabs切换
		var kind_text = '1';
		var page_num = 1;
		$('.select_kind').click(function(){
			page_num=1;
			kind_text = $(this).find('a').attr('title');
			var Hed = $(".select_main").find(".active").find(".a_header").text();
			
					    switch (Hed){
					    	case "交流":  $(".view1").remove() // 
					    		break;
					    	case "事件":   $(".view2").remove()
					    		break;
					    	case "销售":  $(".view3").remove() //
					    		break;
					    	case "退款":  $(".view4").remove()  //
					    		break;
					    	default:
					    		break;
					    }
			list_data();
			
		})
		//点击跟多加载
		function list_view(data){
							 
							
			if($(".timeline").is(".active")){
					    var Hed = $(".select_main").find(".active").find(".a_header").text();
					    
					    
					    switch (Hed){
					    	case "交流":   view1(data) // 
					    		break;
					    	case "事件":   view2(data)
					    		break;
					    	case "销售":   view3(data) //$("#money_yes").prepend(str3)
					    		break;
					    	case "退款":   view4(data)  //
					    		break;
					    	default:
					    		break;
					    }
					    
				   }
		}
		function view1(data){
			for (var i=0;i<data.length;i++) {
				var str = `<li class="view1">
							        <i class="fa fa-comments bg-yellow"></i>
							        <div class="timeline-item">
													<span class="time">
														<i class="fa fa-clock-o"></i>
														${data[i][2]}
													</span>
							            <h3 class="timeline-header"><a href="#">交流</a></h3>
							
							            <div class="timeline-body">
							                		<span>项目名:</span><span>${data[i][0]}</span>
								                	<span>联系人:</span><span>${data[i][1]}</span>
							            </div>
							
							            
							        </div>
							    </li>`;
				$("#comments_text").prepend(str)
			}
		}
		function view2(data){
			var replay_box = "";
			var rep_box ="";
	            
			var Img_arr = "";
			
			console.log(Img_arr)
			for (var i=0;i<data.length;i++) {
				           for (var n =0;n<data[i][6].length;n++) {
								var Img = '<img src="'+data[i][6][n]+'" width="50" />';
								Img_arr+=Img;
							}
			              for (var j=0;j<data[i][7].length;j++) {
				            	for (var m =0;m<data[i][7][j].length;m++) {
				            		if(m!==0){
				            		var rep = ` <li><label>${data[i][7][j][m][0]}：</label><span>${data[i][7][j][m][1]}</span></li> `;
				            		rep_box += rep;
				            		}
				            	}
				            	var replay = `<div class="guide_replay">
													                	<label>${data[i][7][j][0][0]}:</label>
													                	<span class="guide_replay_text">${data[i][7][j][0][1]}</span>
													                	<span class="time">
																			<i class="fa fa-clock-o"></i>
																			${data[i][7][j][0][2]}
																		</span>
													                	<div class="cstm_replay">
													                		<ul class="cstm_replay_text">
																				   ${rep_box}             			
																			</ul>
													                	</div>
													                	<button class="sub_edit cstm_replay_btn" event="${data[i][7][j][0][3]}" id-card="${data[i][8]}">回复</button>
													                </div>`;
							      
							        
								   replay_box += replay;
								   rep_box="";
								   replay ="";
							
			          	 }
			              var str = `<li class="view2">
								        <i class="fa fa-heartbeat bg-green"></i>
								        <div class="timeline-item">
								                        <span class="time">
															<i class="fa fa-clock-o"></i>
															${data[i][4]}
														</span>
								                        <span class="time">
															<i class="fa fa-user-o"></i>
															${data[i][5]}
														</span>
														
								            <h3 class="timeline-header"><a class="a_header" href="#">事件</a></h3>
								
								            <div class="timeline-body">
								                <span>项目名称:</span><span>${data[i][1]}</span>
								                <span>客户名称:</span><span>${data[i][0]}</span>
								                <span>事件类型:</span><span>${data[i][3]}</span><br />
								                <label>事件内容:</label>
								                <div class="event_body">
								                	
								                	<span class="event_text">${data[i][2]}</span>
								                	<div class="event_img">
								                		${Img_arr}
								                	</div>
								                </div>
								                <div class="event_other">
								                	
								                	<span class="event_like event_2"><i class="fa fa-comments"></i>&nbsp评论详情</span>
								                </div>
								                <div class="guild_box">
								                	 ${replay_box}
								                </div>
								                
												<div class="guild_comment input-group input-group-sm">
													<input class="guild_text input-sm form-control" type="text" />
												    <span  class="guild_sub" guild-event="${data[i][9]}" id-card="${data[i][8]}" >
												    	<button type="btn">go</button>
												    </span>
												</div>
								            </div>
								            
								        </div>
								        
								    </li>`;
								    
					replay_box = [];			    
				  $('#now_event').prepend(str);
				  
				}
			      $('.guild_box').hide();
				  submit_comment();
				  look_event_detail(data);
				  submit_call();
		}
		function view3(data){
			for (var i = 0;i<data.length;i++) {
					    	var str = `<li class="view3">
							        <i class="fa fa-money bg-maroon"></i>
							        <div class="timeline-item">
													<span class="time">
														<i class="fa fa-clock-o"></i>
														${data[i][4]}
													</span>
							            <h3 class="timeline-header"><a href="#">销售</a></h3>
							
							            <div class="timeline-body">
							                <span>项目名称:</span><span>${data[i][0]}</span>
							                <span>产品名称:</span><span>${data[i][1]}</span>
							                <div>
							                	<span>销售数量:</span><input class="sale_num" type="text" value="${data[i][2]}" readonly="readonly"/>
							                	<span>销售金额:</span><input class="sale_num" type="text" value="${data[i][3]}" readonly="readonly"/>
							                	<button sale_id="data[i]" class="sub_edit edit1">编辑</button>
							                </div>
							            </div>
							            
							        </div>
							    </li>`;
							    $("#money_yes").prepend(str)
					    }
			money_edit();
		}
		function view4(data){
			for (var i=0;i<data.lenght;i++) {
				       var str = `<li class="view4">
							        <i class="fa fa-envelope bg-aqua"></i>
							        <div class="timeline-item">
													<span class="time">
														<i class="fa fa-clock-o"></i>
														${data[i][4]}
													</span>
							            <h3 class="timeline-header"><a href="#">退款</a></h3>
							
							            <div class="timeline-body">
							                <span>项目名称:</span><span>${data[i][0]}</span>
							                <span>产品名称:</span><span>${data[i][1]}</span>
							                <div>
							                	<span>退款数量:</span><input type="text" value="${data[i][2]}"/>
							                	<span>退款金额:</span><input type="text" value="${data[i][3]}"/>
							                	<button class="sub_edit edit2">编辑</button>
							                </div>
							            </div>
							            
							        </div>
							    </li>`;
				$("#money_no").prepend(str);
			}
		}
		function money_edit(){
			if($.cookie('Right')!=1&&$.cookie('Right')!=2){
					$(".sale_num").attr('readonly',false);
					$(".edit1").click(function(){
						var Sale_id = $(this).attr('sale_id');
						var Sale_len=$(this).parent().parent().find("input");
						
						var Sale_content=[];
						for (var m = 0;m<Sale_len.length;m++) {
							Sale_content[m] = Sale_len.eq(m).val();
							console.log(Sale_content[m])
						}
						$.ajax({
							type:"get",
							url:"http://www.duoweish.com/apis/SalesEdit/",
							data:{
								UserId:$.cookie('ID'),
								Id:Sale_id,
								Info:Sale_content.join('*@*')
							},
							async:true,
							success:function(){
								layer.msg('编辑成功')
								
							}
						});
					})
				}
		}
		function list_data(index){
			
			 
			 $.ajax({
				type:"get",
				url:"http://www.duoweish.com/apis/DwCstmDetailRight/",
				async:true,
				data:{
					UserId:$.cookie('ID'),
					CstmId:cstm_id,
					Kind:kind_text,
					Page:page_num
				},
				success:function(data){
					if(data.length>0){
						page_num++;
				       list_view(data);
					}else{
						layer.msg('没有数据了')
					}
				    
					
				}
			});
		}
		//初始化
		 $.ajax({
				type:"get",
				url:"http://www.duoweish.com/apis/DwCstmDetailRight/",
				async:true,
				data:{
					UserId:$.cookie('ID'),
					CstmId:cstm_id,
					Kind:kind_text,
					Page:page_num
				},
				success:function(data){
					if(data.length>0){
						page_num++;
				       list_view(data);
					}
				    
					
				}
			});
		$('.click_more').click(function(){
			list_data();
			
		})
		
		//提交评论
		function submit_comment(){
			$(".guild_sub").click(function(){
				
				var Card = $(this).attr('id-card');
				var Text = $(this).prev().val();
				console.log(Card)
				if(Card=='2'&&Text!=''){
					    
					    var gu_event = $(this).attr('guild-event');
							$.ajax({
									type:"get",
									url:"http://www.duoweish.com/apis/NewComment/",
									data:{
									    UserId:$.cookie('ID'),
										Event: gu_event,
										Content:Text
										},
									success:function(){
										layer.msg('提交成功');
										}
								});	
				
				       }
				if(Card=='1'||Card=='0'){
				       	layer.msg('提交失败！您没有相关权限')
				       }
				if(Text==''){
					layer.msg('请输入内容后提交');
				}
		          
		   })
		}
		//提交回复
		function submit_call(){
			$('.cstm_replay_btn').click(function(){
				var Guild = $(this).attr('event');
				var Card2 = $(this).attr('id-card');
				if(Card2!='0'){
					 layer.prompt({
						title: '请输入回复内容',
						area: ['300px', '150px']
					    }, function(text, index, value) {
						$.ajax({
							type: "get",
							url: "http://www.duoweish.com/apis/NewReply/",
							data: {
								UserId: $.cookie('ID'),
								Comment: Guild,
								Content: text
							},
							success:function(){
			
								layer.msg('提交成功');
								layer.close(index);
							}
		
					   });
						
					})
				 }else{
				 	layer.msg('提交失败！您没有相关权限');
				 }
			})
		}
		//查看事件评论详情
		function look_event_detail(){
				$(".event_2").click(function(i){
					$(this).parent().next().show();
					 if($(this).parent().next()[0].innerText==''){
					 	layer.msg('该事件目前没有评论')
					 }
					
				})
			
		}
			
		
	}) 
